package com.runchamp.GoogleCloudMessagingUtils;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.apache.http.Header;

import java.io.IOException;

/**
 * Created by User on 12/23/2014.
 */
public class RegisterDevice {

    public static final String PROPERTY_REG_ID = "registration_id";
    public static final String SENDER_ID = "123950685677";
    private static final String PROPERTY_APP_VERSION = "appVersion";
    private static final String REGISTER_DEVICE_URL = "http://runtobo.appspot.com/registerDevice";
    public static String regid;
    private final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
    GoogleCloudMessaging gcm = null;
    private String PREFS_NAME = "MyPrefsFile";



/*
    //on create
    SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
    SharedPreferences.Editor editor = settings.edit();
    editor.remove(PROPERTY_REG_ID);
    // Commit the edits!
            editor.commit();
*/
/*
    //on click
    SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
                                        SharedPreferences.Editor editor = settings.edit();
                                        editor.putString("userID", jsonObject.get("user").toString());
                                        // Commit the edits!
                                                editor.commit();


                                                registerUserDevice();

*/

    /**
     * @return Application's version code from the {@code PackageManager}.
     */
    private static int getAppVersion(Context context) {
        try {
            PackageInfo packageInfo = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            // should never happen
            throw new RuntimeException("Could not get package name: " + e);
        }
    }

    /**
     * Registers the application with GCM servers asynchronously.
     * <p/>
     * Stores the registration ID and the app versionCode in the application's
     * shared preferences.
     */
    private void registerInBackground(final Context context) {
        new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                Log.i("registerInBackground", "Starting registration");
                String msg = "";
                try {

                    gcm = GoogleCloudMessaging.getInstance(context);
                    Log.i("Before register", "regiser..");
                    regid = gcm.register(SENDER_ID);
                    Log.i("RegID", "AFTER");
                    msg = "Device registered, registration ID=" + regid;

                    // For this demo: we don't need to send it because the device will send
                    // upstream messages to a server that echo back the message using the
                    // 'from' address in the message.

                    // Persist the regID  no need to register again.
                    storeRegistrationId(context, regid);

                    // You should send the registration ID to your server over HTTP, so it
                    // can use GCM/HTTP or CCS to send messages to your app.
                    sendRegistrationIdToBackend(context);
                } catch (IOException ex) {
                    msg = "Error :" + ex.getMessage();
                    // If there is an error, don't just keep trying to register.
                    // Require the user to click a button again, or perform
                    // exponential backoff.
                }
                return msg;
            }


            @Override
            protected void onPostExecute(String msg) {
                //  mDisplay.append(msg + "\n");
                Log.i("onPostExecute", msg);
            }
        }.execute(null, null, null);
    }

    //Register device with GCM
    public void registerUserDevice(Context context) {
        if (checkPlayServices(context)) {
            gcm = GoogleCloudMessaging.getInstance(context);
            registerInBackground(context);
            //regid = getRegistrationId(context);
            // if (regid.isEmpty()) {

            //}
        } else {
            Log.i("Login regester device", "No valid Google Play Services APK found.");
        }
    }

    private void sendRegistrationIdToBackend(Context context) {
        Log.i("sendRegistrationIdToBackend", "Sending");
        AsyncHttpClient client = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put("regID", regid);
        SharedPreferences sharedPreferences = context.getSharedPreferences(PREFS_NAME, context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", null);
        if (userID == null) {
            Log.e("Send RegID to server", "No UserID in shared prefs");
        } else {
            params.put("userID", userID);
            client.post(REGISTER_DEVICE_URL, params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    super.onSuccess(statusCode, headers, responseBody);
                    Log.i("Send regId to server", "Success");
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                    super.onFailure(statusCode, headers, responseBody, error);
                    Log.i("Send regId failed", error.toString());
                }
            });
        }
    }

    /**
     * Stores the registration ID and the app versionCode in the application's
     * {@code SharedPreferences}.
     *
     * @param context application's context.
     * @param regId   registration ID
     */
    private void storeRegistrationId(Context context, String regId) {
        final SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, context.MODE_PRIVATE);
        int appVersion = getAppVersion(context);
        Log.i("Store regID", "Saving regId on app version " + appVersion);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(PROPERTY_REG_ID, regId);
        editor.putInt(PROPERTY_APP_VERSION, appVersion);
        editor.commit();
    }

    /**
     * Check the device to make sure it has the Google Play Services APK. If
     * it doesn't, display a dialog that allows users to download the APK from
     * the Google Play Store or enable it in the device's system settings.
     */
    private boolean checkPlayServices(Context context) {
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(context);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                // GooglePlayServicesUtil.getErrorDialog(resultCode, this,PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                Log.i("Login register device", "This device is not supported.");
                //finish();
            }
            return false;
        }
        return true;
    }


    /**
     * Gets the current registration ID for application on GCM service, if there is one.
     * <p/>
     * If result is empty, the app needs to register.
     *
     * @return registration ID, or empty string if there is no existing
     * registration ID.
     */
    private String getRegistrationId(Context context) {
        final SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        String registrationId = prefs.getString(PROPERTY_REG_ID, "");
        if (registrationId.isEmpty()) {
            Log.i("Login register device", "Registration not found.");
            return "";
        }
        // Check if app was updated; if so, it must clear the registration ID
        // since the existing regID is not guaranteed to work with the new
        // app version.
        int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
        int currentVersion = getAppVersion(context);
        if (registeredVersion != currentVersion) {
            Log.i("Login register device", "App version changed.");
            return "";
        }
        return registrationId;
    }


}
